package com.gupaoedu.mvcframework.servlet.v2;

import com.gupaoedu.mvcframework.annotation.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

/**
 * @author fan
 * @version 1.0v
 * @Description TODO
 * @Time 2020-11-20 00:33
 * @Email 44867924@qq.com
 */
public class GPDispatcherServet extends HttpServlet {

    /**
     * 读取properties的工具类 java自带
     */
    private Properties contextConfig = new Properties();

    /**
     * 用来存所有的扫描到的类的全类名
     */
    private List<String> classNames = new ArrayList<>();

    /**
     *
     */
    private Map<String, Object> ioc = new HashMap<>();

    /**
     * handlerMapper容器
     */
    private Map<String, Method> handlerMapper = new HashMap<>();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //　运行阶段
        try {
            doDispatch(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("500 Exception,Detail:" + Arrays.toString(e.getStackTrace()));
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = ("/" + url + "/").replaceAll(contextPath, "").replaceAll("/+", "/");
        if (!this.handlerMapper.containsKey(url)) {
            resp.getWriter().write("404 Not Found");
            return;
        }

        Map<String, String[]> paramsMap = req.getParameterMap();
        Method method = this.handlerMapper.get(url);
        // 还是利用反射，首先拿到形参列表
        Class<?>[] parameterTypes = method.getParameterTypes();
        // 定义实参列表
        Object[] paramsValues = new Object[parameterTypes.length];
        // 根据形参列表给实参列表赋值
        for (int i = 0; i < parameterTypes.length; i++) {
            Class parameterType = parameterTypes[i];
            if (parameterType == HttpServletRequest.class) {
                paramsValues[i] = req;
            } else if (parameterType == HttpServletResponse.class) {
                paramsValues[i] = resp;
            } else if (parameterType == String.class) {
                // 拿到注解
                Annotation[][] pa = method.getParameterAnnotations();
                for (Annotation a : pa[i]) {
                    if (a instanceof GPRequestParam) {
                        String paramName = ((GPRequestParam) a).value();
                        if (!"".equals(paramName.trim())) {
                            String value = Arrays.toString(paramsMap.get(paramName))
                                    .replaceAll("\\[|\\]", "")
                                    .replaceAll("\\s", "");
                            paramsValues[i] = value;

                        }
                    }
                }

            }

        }


        String beanName = toLowerFirstCase(method.getDeclaringClass().getSimpleName());
        // 这里硬编码
        // method.invoke(ioc.get(beanName),new Object(){},params.get("name")[0],params.get("id")[0]);
        // 动态编码
        method.invoke(ioc.get(beanName), paramsValues);


    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 初始化阶段
        // １：加载配置文件
        // 读取web.xml中这个contextConfgLocation ---->　得到对应的值　　application.properties
        doLoadConfig(config.getInitParameter("contextConfigLocation"));
        // 得到一个文件流

        // 2: 扫描相关的类
        //这里是读取配置文件：application.properties,scanpackage是一个key,得到一个包路径，然后把他转成一个文件路径
        doSanner(contextConfig.getProperty("scanPackage"));

        // 实例化相关的类并且缓存到ioc容器中
        doInstance();

        // 完成依赖注入
        doAutowired();
        // 初始化handlerMapper
        doInitHanderMapper();
        // 初始化阶段完成
        System.out.println("GP spring framework is init");


    }

    private void doInitHanderMapper() {
        if (ioc.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();
            if (!clazz.isAnnotationPresent(GPController.class)) {
                continue;
            }

            // 如果还有直接加到类上的
            String baseUrl = "";
            if (clazz.isAnnotationPresent(GPRequestMapping.class)) {
                GPRequestMapping requestMapping = clazz.getAnnotation(GPRequestMapping.class);
                baseUrl = requestMapping.value();
            }


            // 得到所有的public 方法
            for (Method method : clazz.getMethods()) {
                System.out.println(method.isAnnotationPresent(GPRequestMapping.class));
                if (!method.isAnnotationPresent(GPRequestMapping.class)) {
                    return;
                }
                GPRequestMapping requestMapping = method.getAnnotation(GPRequestMapping.class);
                // 防止多个斜线
                String url = ("/" + baseUrl + "/" + requestMapping.value()).replaceAll("/+", "/");
                handlerMapper.put(url, method);
                System.out.println("Mapper : " + url + "," + method);
            }

        }
    }

    private void doAutowired() {
        if (ioc.isEmpty()) {
            return;
        }

        // ioc是里面所有的加了注解的对应的类
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            // 得到所有字段，　包括　public priviate protected default
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for (Field field : fields) {
                // 只有加了这个注解的，才给他自动赋值
                if (!field.isAnnotationPresent(GPAutowired.class)) {
                    continue;
                }
                GPAutowired autowired = field.getAnnotation(GPAutowired.class);
                // 看有没有自定义的
                String beanName = autowired.value().trim();
                if ("".equals(beanName)) {
                    beanName = field.getType().getName();
                }

                //　强制访问，
                field.setAccessible(true);
                try {
                    /*
                     filed 相当于　
                     @GPAutowired
                     private IDemoService demoService
                     */
                    // entry.getValue() ===> DemoAction 实例
                    // ioc.get(beanName) ===>ioc.get( com.gupaoedu.mvcframework.servlet.IDemoService)
                    System.out.println(beanName);
                    // 这里得到的结果为null
                    System.out.println(ioc.get(beanName));
                    field.set(entry.getValue(), ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    continue;
                }
            }
        }
    }

    private void doInstance() {
        if (classNames.isEmpty()) {
            return;
        }
        try {
            for (String className : classNames) {
                Class<?> clazz = Class.forName(className);

//                if(clazz.isAnnotationPresent(GPController.class)|| clazz.isAnnotationPresent(GPService.class)){
//
//                }
                // TODO 把controller 和 service　分别处理
                // 只有加了对应的注解才实例化
                if (clazz.isAnnotationPresent(GPController.class)) {

                    // spring　官方以类名首字母小写为ioc　容器中，实例对象的key值
                    String beanName = toLowerFirstCase(clazz.getSimpleName());
                    Object instance = clazz.newInstance();

                    ioc.put(beanName, instance);
                } else if (clazz.isAnnotationPresent(GPService.class)) {

                    // spring　官方以类名首字母小写为ioc　容器中，实例对象的key值
                    String beanName = toLowerFirstCase(clazz.getSimpleName());
                    Object instance = clazz.newInstance();
                    // 不同包名下重名，就自定义beanName;
                    GPService service = clazz.getAnnotation(GPService.class);
                    // 不为空
                    if (!"".equals(service.value())) {
                        // 替换为自定义的的beanName
                        beanName = service.value();
                    }
                    ioc.put(beanName, instance);
                    // 全类名，就是以接口注入，子类来实现　
                    for (Class<?> i : clazz.getInterfaces()) {
                        // 一个接口有两个实现类的时候，抛出异常，请走自定义beanName
                        if (ioc.containsKey(i.getName())) {
                            throw new Exception("This beanName is exists");
                        }
                        ioc.put(i.getName(), instance);
                    }


                } else {
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 首字母小写
    private String toLowerFirstCase(String simpleName) {
        char[] chars = simpleName.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

    private void doLoadConfig(String contextConfgLocation) {
        // 加载配置文件
        // 在classPath去找
        // 变成一个文件流
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(contextConfgLocation);
        try {
            contextConfig.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    private void doSanner(String scanPackage) {
        // 用正则，把点变成'/'
        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        // 把这个url变成一个文件
        //得到这个文件的路径
        File classPth = new File(url.getFile());
        for (File file : classPth.listFiles()) {
            // 这里的file有文件，也有文件夹
            if (file.isDirectory()) {
                doSanner(scanPackage + "." + file.getName());
            } else {
                // 一个文件夹下面会有各种各样的文件 这里只要以.class结尾的文件
                if (!file.getName().endsWith(".class")) {
                    continue;
                }
                // 得到他的全类名
                String fileName = (scanPackage + "." + file.getName().replace(".class", ""));
                // Class.forName();
                classNames.add(fileName);
            }
        }
    }
}
